package br.com.felix.fwt.ui;

import java.io.PrintWriter;

import br.com.felix.fwt.ui.exception.ComponentRenderException;

/**
 * The Class Button implements the HTML input of the type button or image.
 * If you define the image property, than it will be of the type image.
 * Button otherwise.
 * <p>
 * This is currently the only class that implements behavior for the action listener.
 * If the actionListener is not null, this class will evoke a form submit on the click event.
 * </p>
 */
public class IconButton extends BaseComponent {

	private static final long serialVersionUID = -4009374434389383949L;

	public boolean displayOnPresentationModeShow = true;
	
	/** The image. */
	public Image image;

	{
	    this.cssClass = "fwticonbutton";
	}
	
	
	/**
	 * Instantiates a new button.
	 */
	public IconButton(){
	}
	
	/**
	 * Instantiates a new button.
	 * 
	 * @param name the name
	 * @param value the value
	 */
	public IconButton(String value, Image image){
		this();
		this.setValue(value);
		this.image=image;
	}

	
	
	/* (non-Javadoc)
	 * @see br.com.felix.fwt.ui.BaseComponent#write(java.io.PrintWriter)
	 */
	@Override
	public void write(PrintWriter out) throws ComponentRenderException {
		if(!authorized()) return;
		String value = getValue();
		switch(getPresentationMode()){
			case SHOW:
				if(!displayOnPresentationModeShow)break;
			case EDIT:
			case DELETED:
				out.write("\n<div class=\"");
				out.write(cssClass);
				out.write("\" id=\"");
				out.write(getName());
				out.write("\"");
				if(style!=null){
					out.write(style);
				}
				else{
					out.write(" style=\"cursor:pointer;\" ");
				}
				if(this.actionListener!=null){
					actionListener.write(out);
				}
				out.write(">");
				out.write("\n<img src=\"");
				out.write(image.getValue());
				out.write("\" alt=\"");
				out.write(value);
				out.write("\" />");
				out.write(value);		
				out.write("\n</div>");
		}
	}

	
	
	@Override
	public boolean equals(Object obj) {
		if(obj==null)return false;
		if(!(obj instanceof IconButton))return false;
		IconButton btn = (IconButton)obj;	
		String name = getName();
		String btnName = btn.getName();
		if(btnName==null || name ==null)return false;
		return name.equals(btnName);
	}

	
	@Override
	public int hashCode() {
	    String name = getName();
		if(name!=null){
			return name.hashCode();
		}
		return super.hashCode();
	}
}
